package com.hzhk.happyrent.ui.activity.rent;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.Constants;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.OrderPlaceBean;
import com.hzhk.happyrent.bean.ResContainerModel;
import com.hzhk.happyrent.bean.ZMModel;
import com.hzhk.happyrent.bean.person.UserInfoModel;
import com.hzhk.happyrent.bean.rent.ProductInfoModel;
import com.hzhk.happyrent.bean.rent.ProductInfoModel.DataBean.GoodsBean.SpecArrayBean;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.activity.ConfirmActivity;
import com.hzhk.happyrent.ui.activity.personal.LoginActivity;
import com.hzhk.happyrent.ui.activity.personal.PersonInfoActivity;
import com.hzhk.happyrent.ui.adapter.MoreServiceAdapter;
import com.hzhk.happyrent.ui.adapter.person.ProductTypeAdapter;
import com.hzhk.happyrent.ui.adapter.viewpager.ModelPagerAdapter;
import com.hzhk.happyrent.ui.adapter.viewpager.PicAdapter;
import com.hzhk.happyrent.ui.fragment.ProductPicFragment;
import com.hzhk.happyrent.ui.view.MyListView;
import com.hzhk.happyrent.ui.view.PullUpToLoadMore;
import com.hzhk.happyrent.ui.view.indicator.SpringIndicator;
import com.hzhk.happyrent.utils.ListUtils;
import com.hzhk.happyrent.utils.MyPerference;
import com.tamic.novate.Throwable;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ProductDetailsActivity extends AppCompatActivity implements ProductTypeAdapter.ButtonSelecterListener {

    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.activity_titlebar_right)
    ImageView activityTitlebarRight;
    @BindView(R.id.choose_type)
    TextView chooseType;
    @BindView(R.id.service_more)
    MyListView serviceMore;
    @BindView(R.id.act_login_submit)
    Button actLoginSubmit;
    @BindView(R.id.product_name)
    TextView productName;
    @BindView(R.id.product_price_single)
    TextView productPriceSingle;
    @BindView(R.id.product_price_total)
    TextView productPriceTotal;
    @BindView(R.id.product_description)
    TextView productDescription;
    @BindView(R.id.vp_product_pic)
    ViewPager vpProductPic;
    @BindView(R.id.choose_ready)
    TextView chooseReady;
    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.show_or_hind)
    LinearLayout showOrHind;
    @BindView(R.id.layout_product_type)
    MyListView layoutProductType;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.indicator)
    SpringIndicator indicator;
    @BindView(R.id.pull_up_to_load_more)
    PullUpToLoadMore pullUpToLoadMore;
    @BindView(R.id.tv_service_more)
    TextView tvServiceMore;
    @BindView(R.id.choose_please)
    RelativeLayout choosePlease;
    @BindView(R.id.img_more)
    ImageView imgMore;
    @BindView(R.id.info_more)
    TextView infoMore;

    private PicAdapter picAdapter;
    private String choosed = "";
    private String rentCount = "";
    private String goods_id;
    private MoreServiceAdapter moreServiceAdapter;
    private String goods_sku_id;
    private ProductTypeAdapter productTypeAdapter;
    private String message;
    private String serviceId;
    private List<Fragment> fragments;
    private ModelPagerAdapter adapter;
    private String zmGrade;
    private String orderId = "";
    private String wx_pay_price;
    private String price;
    private String zu_money_total;
    private String service_money;

    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                initFragment();
                imgMore.setImageDrawable(getResources().getDrawable(R.drawable.more_hide));
                infoMore.setText("下拉收起图文详情");
            } else if (msg.what == 2) {
                imgMore.setImageDrawable(getResources().getDrawable(R.drawable.list_more));
                infoMore.setText("上拉查看图文详情");
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_buy);
        ButterKnife.bind(this);
        initView();
        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.GOODS_ID))) {
            goods_id = getIntent().getStringExtra(Constants.GOODS_ID);
            if (!TextUtils.isEmpty(MyPerference.getInstance().getUserId())) {
                infomation_judge();
            }
            initData();
        } else {
            Toast.makeText(this, "商品错误", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initView() {
        activityTitlebarLeft.setImageResource(R.drawable.back);
        activityTitlebarCenter.setText(R.string.product_name);
        activityTitlebarRight.setVisibility(View.GONE);
        picAdapter = new PicAdapter(this);
        vpProductPic.setAdapter(picAdapter);

        moreServiceAdapter = new MoreServiceAdapter(this);
        serviceMore.setAdapter(moreServiceAdapter);

        productTypeAdapter = new ProductTypeAdapter(this);
        layoutProductType.setAdapter(productTypeAdapter);

//       myListView.setAdapter(productTypeAdapter);

        serviceMore.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String is_need = ((MoreServiceAdapter) (adapterView.getAdapter())).getItem(i).getIs_need();
                if (!"1".equals(is_need)) {
                    boolean choose = ((MoreServiceAdapter) (adapterView.getAdapter())).getItem(i).isChoose();
                    ((MoreServiceAdapter) (adapterView.getAdapter())).getItem(i).setChoose(!choose);
                    moreServiceAdapter.notifyDataSetChanged();
                    refreshChoose();
                }
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ((ProductPicFragment) fragments.get(position)).setViewListenenr(pullUpToLoadMore);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        indicator.initSpringView();

//        fragments = new ArrayList<>();
//        fragments.add(new ProductPicFragment());
//        fragments.add(new ProductPicFragment());
//        adapter = new ModelPagerAdapter(getSupportFragmentManager(), fragments, this);
//        viewPager.setAdapter(adapter);
//        // just set viewPager
//        indicator.setViewPager(viewPager);
    }

    private void initFragment() {
        if (fragments == null) {
            fragments = new ArrayList<>();
            fragments.add(new ProductPicFragment());
            fragments.add(new ProductPicFragment());
            adapter = new ModelPagerAdapter(getSupportFragmentManager(), fragments, this);
            viewPager.setAdapter(adapter);
            // just set viewPager

            indicator.setViewPager(viewPager);
            indicator.setVisibility(View.VISIBLE);
            ProductPicFragment productPicFragment = (ProductPicFragment) fragments.get(0);
            productPicFragment.setViewListenenr(pullUpToLoadMore);
            productPicFragment.setWebView(productInfoModel.getData().getGoods().getGoods_content());
            productPicFragment = (ProductPicFragment) fragments.get(1);
            productPicFragment.setWebView(productInfoModel.getData().getGoods().getGoods_paramers());
        }
    }

    private ProductInfoModel productInfoModel;

    private void initData() {
        Map<String, Object> params = new HashMap<>();
        params.put("goods_id", getIntent().getStringExtra(Constants.GOODS_ID));
        if (!TextUtils.isEmpty(MyPerference.getInstance().getUserId())) {
            params.put("user_id", MyPerference.getInstance().getUserId());
        }
        HttpManager.getInstance().get(API.GOODS_DETAIL, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                productInfoModel = new Gson().fromJson(response, ProductInfoModel.class);
                picAdapter.setData(productInfoModel.getData().getGoods().getPreview_goods_extend_image());
                initText();
//                initFragment();
            }
        });
    }


    private void initText() {
        productName.setText(productInfoModel.getData().getGoods().getGoods_name());
        productPriceSingle.setText(productInfoModel.getData().getGoods().getGoods_sell_price());
        productPriceTotal.setText(productInfoModel.getData().getGoods().getGoods_cost_price());
        productDescription.setText(productInfoModel.getData().getGoods().getGoods_sub_title());
        if (!ListUtils.isEmpty(productInfoModel.getData().getGoods_added_service())) {
            tvServiceMore.setVisibility(View.VISIBLE);
            moreServiceAdapter.setList(productInfoModel.getData().getGoods_added_service());
        } else {
            tvServiceMore.setVisibility(View.GONE);
        }
        productTypeAdapter.setList(productInfoModel.getData().getGoods().getSpec_array());
        message = "";
        for (SpecArrayBean specArrayBean : productInfoModel.getData().getGoods().getSpec_array()) {
            message += specArrayBean.getName() + "、";
        }
        if (!ListUtils.isEmpty(productInfoModel.getData().getGoods_added_service())) {
            for (ProductInfoModel.DataBean.GoodsAddedServiceBean goodsAddedServiceBean : productInfoModel.getData().getGoods_added_service()) {
                if ("1".equals(goodsAddedServiceBean.getIs_need())) {
                    message += "增值服务、";
                    break;
                }
            }
        }
        productPriceSingle.setText(productInfoModel.getData().getGoods().getGoods_sell_price());
        if (!TextUtils.isEmpty(message)) {
            message = message.substring(0, message.length() - 1);
            chooseType.setText(message);
        }
    }

    private void getService() {
        message = "";
        serviceId = "";
        if (!ListUtils.isEmpty(productInfoModel.getData().getGoods_added_service())) {
            for (ProductInfoModel.DataBean.GoodsAddedServiceBean goodsAddedServiceBean : productInfoModel.getData().getGoods_added_service()) {
                if ("1".equals(goodsAddedServiceBean.getIs_need())) {
                    serviceId += goodsAddedServiceBean.getId() + ",";
                    message += goodsAddedServiceBean.getName() + ",";
                }
            }
        }
    }


    private void refreshChoose() {
        choosed = "";
        for (SpecArrayBean specArrayBean : productInfoModel.getData().getGoods().getSpec_array()) {
            if (!TextUtils.isEmpty(specArrayBean.getSelect())) {
                if ("租期".equals(specArrayBean.getName())) {
                    choosed += specArrayBean.getSelect() + "、";
                    rentCount = specArrayBean.getSelect();
                } else {
                    choosed += specArrayBean.getSelect() + "、";
                }
            } else {
                return;
            }
        }
        if (!TextUtils.isEmpty(choosed)) {
            getService();
            if (!TextUtils.isEmpty(message)) {
                choosed += message;
            }
            chooseType.setText(choosed.substring(0, choosed.length() - 1));
            chooseReady.setText(R.string.product_choosed);
            chooseReady.setTextColor(getResources().getColor(R.color.tab_red));
        } else {
            chooseType.setText(message);
            chooseReady.setText(R.string.product_choose_p);
            chooseReady.setTextColor(getResources().getColor(R.color.black_80));
        }
        judgeIt();
    }


    @OnClick({R.id.activity_titlebar_left, R.id.act_login_submit
            , R.id.choose_please
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.act_login_submit:
                if (!TextUtils.isEmpty(MyPerference.getInstance().getUserId())) {
                    if (Constants.AUTH_YES.equals(MyPerference.getInstance().getAuth())) {
                        placeAnOrder();
//                        startActivity(new Intent(this, ConfirmActivity.class));
//                        doVerify("https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=2017121200620046&redirect_uri=http%3A%2F%2Fexample.com");
                    } else if (Constants.AUTH_CHECKING.equals(MyPerference.getInstance().getAuth())) {
                        Toast.makeText(this, R.string.person_info_checking, Toast.LENGTH_SHORT).show();
                    } else {
                        startActivity(new Intent(ProductDetailsActivity.this, PersonInfoActivity.class));
                    }
                } else {
                    startActivity(new Intent(ProductDetailsActivity.this, LoginActivity.class));
                }
                break;
        }
    }

    private void zm_grade() {
        if (TextUtils.isEmpty(goods_sku_id)) {
            Toast.makeText(this, R.string.product_choose_please, Toast.LENGTH_SHORT).show();
            return;
        }
//        placeAnOrder();
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_SCORE_GET, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
//                    ZMModel zmModel=new Gson().fromJson(response, ZMModel.class);
//                    Intent intent = new Intent(ProductDetailsActivity.this, ConfirmActivity.class);
//                    intent.putExtra("zm_grade", zmModel.getData());
//                    startActivityForResult(intent, 1);
//                    finish();
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    zmGrade = zmModel.getData();
                    zhima_cer();
                } else {
                    doit();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });

    }

    private void zm_grade_check() {

        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_SCORE_GET, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    zmGrade = zmModel.getData();
                    zhima_cer();
//                    Intent intent = new Intent(ProductDetailsActivity.this, ConfirmActivity.class);
//                    intent.putExtra("zm_grade", zmModel.getData());
//                    startActivityForResult(intent, 1);
//                    finish();
                } else {
                    Toast.makeText(ProductDetailsActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });

    }

    public void zhima_cer() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
//        params.put("url", "myscheme://www.orangecpp.com:80/mypath?key=mykey");
        HttpManager.getInstance().perform_post(API.ZHIMA_CER, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                Log.i("----error", e.getMessage());
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                Log.i(TAG, "onNext: " + response);
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    doVerify(zmModel.getData());
                } else {
                    Toast.makeText(ProductDetailsActivity.this, codeModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivityForResult(action, 2);
        } else {
            //处理没有安装支付宝的情况
            new AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }

    private void actionTo() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_CER_QUERY, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
//                    Toast.makeText(ProductDetailsActivity.this, codeModel.getMessage(), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ProductDetailsActivity.this, ConfirmActivity.class);
                    intent.putExtra("order_id", orderId);
                    intent.putExtra("zm_grade", zmGrade);
                    intent.putExtra("product_image", productInfoModel.getData().getGoods().getGoods_image());
                    intent.putExtra("product_title", productInfoModel.getData().getGoods().getGoods_name());
                    intent.putExtra("product_description", chooseType.getText().toString());
                    intent.putExtra("product_money", productPriceTotal.getText().toString());
                    intent.putExtra("rent_count", rentCount);
                    intent.putExtra("rent_total", zu_money_total);
                    intent.putExtra("rent_money", price);
                    intent.putExtra("pay_total", wx_pay_price);
                    intent.putExtra("rent_service_more", service_money);
                    intent.putExtra("goods_id", productInfoModel.getData().getGoods().getId());
                    intent.putExtra("goods_sku_id", goods_sku_id);
                    intent.putExtra("service_id", serviceId.substring(0, serviceId.length() - 1));
                    startActivity(intent);
                    finish();
                } else {
                    resultDialog();
                    //Toast.makeText(ProductDetailsActivity.this, "认证失败，请确保实名信息与支付宝信息一致！", Toast.LENGTH_SHORT).show();
                }
//                Intent intent = new Intent(ProductDetailsActivity.this, ConfirmActivity.class);
//                intent.putExtra("order_id", orderId);
//                intent.putExtra("zm_grade", zmGrade);
//                intent.putExtra("product_image", productInfoModel.getData().getGoods().getGoods_image());
//                intent.putExtra("product_title", productInfoModel.getData().getGoods().getGoods_name());
//                intent.putExtra("product_description", chooseType.getText().toString());
//                intent.putExtra("product_money", productPriceTotal.getText().toString());
//                intent.putExtra("rent_count", rentCount);
//                intent.putExtra("rent_total", zu_money_total);
//                intent.putExtra("rent_money", price);
//                intent.putExtra("pay_total", wx_pay_price);
//                intent.putExtra("rent_service_more", service_money);
//                intent.putExtra("goods_id", productInfoModel.getData().getGoods().getId());
//                intent.putExtra("goods_sku_id", goods_sku_id);
//                intent.putExtra("service_id", serviceId.substring(0, serviceId.length() - 1));
//                startActivity(intent);
//                finish();
            }
        });
    }

    private void resultDialog() {
        final Dialog dialog = new Dialog(this, R.style.selectorDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);//点击弹框外不退出
        dialog.setCancelable(false);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(ResContainerModel.getResourceId(this, ResContainerModel.ResType.LAYOUT, "activity_init_dialog"), null);
        dialog.setContentView(view);
        dialog.show();
        Button confirm = ((Button) view.findViewById(ResContainerModel.getResourceId(this, ResContainerModel.ResType.ID, "confirm")));
        if (confirm != null) {
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
    }

    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List<ResolveInfo> list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

    private void doit() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_AUTH, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                Log.i(TAG, "onNext: " + response);
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    Intent intent = new Intent(ProductDetailsActivity.this, LoadWebViewActivity.class);
                    intent.putExtra("uil", zmModel.getData());
                    intent.putExtra("name", "芝麻授权");
                    startActivityForResult(intent, 1);
                }
            }
        });
    }

    private void infomation_judge() {
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.USER_ID, MyPerference.getInstance().getUserId());
        HttpManager.getInstance().get(API.GET_USER_INFO, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                UserInfoModel userInfoModel = new Gson().fromJson(response, UserInfoModel.class);
                if (Constants.AUTH_YES.equals(userInfoModel.getData().getIs_auth())) {
                    MyPerference.getInstance().setAuth(userInfoModel.getData().getIs_auth());
                } else if (Constants.AUTH_CHECKING.equals(userInfoModel.getData().getIs_auth())) {
                    MyPerference.getInstance().setAuth(userInfoModel.getData().getIs_auth());
                    actLoginSubmit.setText(R.string.info_checking);
                } else if (Constants.AUTH_NO.equals(userInfoModel.getData().getIs_auth())) {
                    MyPerference.getInstance().setAuth(Constants.AUTH_NO);
                }
            }
        });
    }

    private void placeAnOrder() {
        if (TextUtils.isEmpty(goods_sku_id)) {
            Toast.makeText(this, R.string.product_choose_please, Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("goods_id", goods_id);
        params.put("goods_sku_id", goods_sku_id);
        params.put("pay_type", "3");
        double mon = Double.parseDouble(productPriceTotal.getText().toString());
        for (ProductInfoModel.DataBean.GoodsAddedServiceBean goodsAddedServiceBean : productInfoModel.getData().getGoods_added_service()) {
            if (goodsAddedServiceBean.isChoose()) {
                mon += Double.parseDouble(goodsAddedServiceBean.getPrice());
            }
        }
        params.put("money", mon);
        params.put("zu_date", rentCount);
        if (!TextUtils.isEmpty(serviceId)) {
            params.put("service_id", serviceId.substring(0, serviceId.length() - 1));
        }
        HttpManager.getInstance().perform_post(API.ORDER_SUB, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                Toast.makeText(ProductDetailsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String message) {
                CodeModel codeModel = new Gson().fromJson(message, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    OrderPlaceBean orderPlaceBean = new Gson().fromJson(message, OrderPlaceBean.class);
                    orderId = orderPlaceBean.getData().getOrder_id();

                    wx_pay_price = orderPlaceBean.getData().getWx_pay_price();
                    price = orderPlaceBean.getData().getPrice();
                    zu_money_total = orderPlaceBean.getData().getZu_money_total();
                    service_money = orderPlaceBean.getData().getService_money();

                    zm_grade();
//                    serviceMoney=Double.parseDouble(orderPlaceBean.getData().getService_money());

                    //测试
//                    testDo();
//                    Toast.makeText(ProductDetailsActivity.this, R.string.product_rent_success, Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(ProductDetailsActivity.this, HomeActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(intent);
                } else {
                    Toast.makeText(ProductDetailsActivity.this, codeModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 1) {
                zm_grade_check();
            } else {
                Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == 2) {
            actionTo();
        }
    }


    private void judgeIt() {
        String getSkuId = "";
        for (SpecArrayBean specArrayBean : productInfoModel.getData().getGoods().getSpec_array()) {
            if (TextUtils.isEmpty(specArrayBean.getSelect())) {
                return;
            } else {
                getSkuId += "[" + specArrayBean.getSelect() + "]";
            }
        }
        getSkuId(getSkuId);
    }

    private void getSkuId(String getSkuId) {
        for (ProductInfoModel.DataBean.GoodsSkuBean goodsSkuBean : productInfoModel.getData().getGoods_sku()) {
            if (getSkuId.equals(goodsSkuBean.getAttr_key_path())) {
                goods_sku_id = goodsSkuBean.getId();
                productPriceSingle.setText(goodsSkuBean.getPrice());
                productPriceTotal.setText(goodsSkuBean.getCost_price());
                break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(MyPerference.getInstance().getUserId())) {
            infomation_judge();
        }
    }

    @Override
    public void refresh() {
        refreshChoose();
    }

}
